package com.z.redis.command.impl;

import com.z.redis.RedisCore;
import com.z.redis.command.CommandType;
import com.z.redis.command.WriteCommand;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.datatype.RedisData;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.RespInt;
import io.netty.channel.ChannelHandlerContext;


/**
 * 处理 Redis 的 EXPIRE 命令，为指定键设置生存时间（TTL）
 */
public class Expire implements WriteCommand {
    private BytesWrapper key; // 设置过期时间的键
    private int second; // 过期时间

    @Override
    public CommandType type(){
        return CommandType.expire;
    }

    @Override
    public void setContent(Resp[] array){
        key = ((BulkString)array[1]).getContent(); // 解析键名
        second = Integer.parseInt(((BulkString) array[2]).getContent().toUTF8String());
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData == null){
            ctx.writeAndFlush(new RespInt(0));
        }else {
            redisData.setTimeout(System.currentTimeMillis() + (second * 1000));
            ctx.writeAndFlush(new RespInt(1));
        }
    }

    @Override
    public void handle(RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData != null){
            redisData.setTimeout(System.currentTimeMillis() + (second * 1000));
        }
    }
}
